﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Model;
namespace AuthServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {

        private static DataAccess.BooksContext m_DbContext;
        private IOptions<Audience> m_Settings;

        public AuthController(IOptions<Audience> m_Setting)
        {
            DataAccess.BooksContext booksContext = new DataAccess.BooksContext();
            m_DbContext = booksContext;
            m_Settings = m_Setting;

        }

        /// <summary>
        /// 验证用户名和密码并生成token
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(string username,string password)
        {

            //验证登录用户名和密码
            var user = m_DbContext.Users.Where(c => c.Username == username && c.Password == password).FirstOrDefault();
            if (user != null)
            {
                var now = DateTime.UtcNow; //添加用户的信息，转成一组声明，还可以写入更多用户信息声明
                var claims = new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, username),//声明主题
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),//JWT ID 唯一标识符
                    new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)//发布时间戳 issued timestamp
                };

                //下面使用 Microsoft.IdentityModel.Tokens帮助库下的类来创建JwtToken
                //创建安全秘钥
                var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
                    System.Text.Encoding.ASCII.GetBytes(m_Settings.Value.Secret));

                var jwt = new JwtSecurityToken(
                    issuer: m_Settings.Value.Iss,//jwt签发人
                    audience: m_Settings.Value.Aud,//jwt受众
                    claims: claims,//jwt一组声明
                    notBefore: now,
                    expires: now.Add(TimeSpan.FromMinutes(20)),//jwt令牌过期时间
                    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)//签名凭证: 安全密钥、签名算法
                );

                //生成jwt令牌(json web token)
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
                var responseJson = new
                {
                    access_token = encodedJwt,
                    expires_in = (int)TimeSpan.FromMinutes(2).TotalSeconds
                };

                return Json(responseJson);
            }
            else
            {
                return Json("");
            }
        }

        /// <summary>
        /// 返回json格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private IActionResult Json(object value)
        {
            return new JsonResult(value);
        }
    }
}